package com.xaicode.learn.netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * netty http example, test on browser 'http://localhost:8888'
 *
 * @author Locker xaicode@sina.com
 * @version 1.0
 * @date 2021/6/15 0015 23:54
 */
public class NettyHttpServer {

    public static void main(String[] args) {

        // create boss group and worker group
        // boss group deal with accepting
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        // worker group deal with business
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {

            // create server bootstrap
            final ServerBootstrap bootstrap = new ServerBootstrap();
            // bind boss and worker
            bootstrap.group(bossGroup, workerGroup);
            // boss group config
            bootstrap
                    // server use nio socket channel
                    .channel(NioServerSocketChannel.class);
            // worker group config
            bootstrap
                    // set worker group`s event pipeline
                    .childHandler(new NettyHttpServerInitializer());

            // sync bind port and start server
            final ChannelFuture channelFuture = bootstrap.bind(8888).sync();

            // listen closed channel
            channelFuture.channel().closeFuture().sync();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

    }

}
